package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AddEmplyeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.UpdateEmplyeeDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.MD5Util;
import com.sky.vo.EmployeePageQueryVO;
import com.sky.vo.EmployeeQueryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String passwordInput = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 数据库中的密码是md5加密的，前端用户的密码是明文的，需要先md5再比对
        String passwordDB = employee.getPassword();
        String md5Password = MD5Util.md5(passwordInput);
        if (!Objects.equals(passwordDB, md5Password)) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }



    @Override
    public void addEmployee(AddEmplyeeDTO dto) {
        // 参数校验
//        String username = dto.getUsername();
//        if(!StringUtils.hasLength(username)){
//           throw new BaseException("用户名不能为空");
//        }
//        if(username.length() < 2 || username.length() > 10){
//            throw new BaseException("用户名长度需要在2-10之间");
//        }
//        String name = dto.getName();
//        if(!StringUtils.hasLength(name)){
//            throw new BaseException("姓名不能为空");
//        }
//        if(name.length() < 2 || name.length() > 10){
//            throw new BaseException("姓名长度需要在2-10之间");
//        }
//        String phone = dto.getPhone();
//        if(!StringUtils.hasLength(phone)){
//            throw new BaseException("手机号不能为空");
//        }
        // 方法1：推荐，先校验名称是否重复，如果重复，抛异常
        Employee employeeDB =  employeeMapper.getByUsername(dto.getUsername());
        if(employeeDB != null){
            // 说名用户名重复
            throw new BaseException("用户名重复");
        }
        // 方法2：抛异常，交给全局异常处理器处理
        Employee employee = new Employee();
        // 属性的copy
        BeanUtils.copyProperties(dto, employee);
        employee.setSex(dto.getSex()+"");
        employee.setPassword(MD5Util.md5(PasswordConstant.DEFAULT_PASSWORD));
        employee.setStatus(StatusConstant.ENABLE);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        // 从request的header中拿到token，解析token，为了拿到当前登录用户的id
//        String token = request.getHeader(JwtClaimsConstant.TOKEN);
//        // 解析token
//        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
//        // 拿到了当前登录用户的id
//        Long empId = claims.get(JwtClaimsConstant.EMP_ID, Long.class);
        // 从当前线程中获取登录的用户的ID
        Long empId = BaseContext.getCurrentId();
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult<EmployeePageQueryVO> page(EmployeePageQueryDTO dto) {
        // 开启分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        // 查询
        Page<EmployeePageQueryVO> page = employeeMapper.pageQuery(dto);
        // 封装返回值
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public void enableOrDisable(Long id, Integer status) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    public EmployeeQueryVO getById(Long id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public void update(UpdateEmplyeeDTO dto) {
        // 用户名不能重复
        // 根据参数中的用户名查数据库
        Employee employeeDB = employeeMapper.getByUsername(dto.getUsername());
        // 查不到，ok
        if(employeeDB == null){
            // ok
        }else{
            // 查到了，判断是不是自己
            if(Objects.equals(dto.getId(), employeeDB.getId())){
                // 如果是自己，允许
            }else{
                // 如果不是自己，说明把名称改成了数据库中已经存在的另外一个用户的名称，error
                throw new BaseException("用户名已经存在");
            }
        }
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);
        employee.setSex(dto.getSex()+"");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }
}
